package com.imooc.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * FileName: SellContextHelper.java
 * Description: TODO
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/28
 */
@Component
public final class SellContextHelper implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    /**
     * 获取ApplicationContext
     * @return
     */
    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * 获取bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    /**
     * 获取HTTP请求
     * @return
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes)
                (Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))).getRequest();
    }

    /**
     * 获取应用的地址
     * @return
     */
    public static String getAppContextPathUrl() {
        HttpServletRequest request = SellContextHelper.getRequest();
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    }
}
